package response;

import java.util.Arrays;

import protocol.CtfActionException;
import structures.Position;
import utils.Conversions;

/**
 * Represents the server response to a BLAST message type (5). 
 * 		Row
 * 			 0	invalid action (i.e. location is not a wall)
 * 			 +	row #
 * 		Column
 * 			 0 invalid action
 * 			 +	column #
 */
public class BlastBody {
	public static final int LENGTH = 4;
	
	/* Derived field */
	Position blastedPos;
	
	public Position getPosition() { return blastedPos; }
	
	/**
	 * Parses the received byte array. (Client usage)
	 * @param response
	 * @throws CtfActionException
	 */
	public BlastBody( byte[] response ) throws CtfActionException {
		// partition field bytes
		byte[] rowInBytes = Arrays.copyOfRange(response, 0, 2);
		byte[] colInBytes = Arrays.copyOfRange(response, 2, 4);
		// convert to int
		int row = Conversions.bytesToInt(rowInBytes);
		int col = Conversions.bytesToInt(colInBytes);
		// invalid move
		if ( row == -1 )
			throw new CtfActionException("5:blast");
		// moved to this position
		blastedPos = new Position( row, col );
	}	
	
	/**
	 * Set blastedPos field. (Server usage)
	 * @param pos
	 */
	public BlastBody( Position pos ) {
		blastedPos = pos;
	}
	
	/**
	 * Converts the BLAST body into a byte array in network byte order.
	 * (Server usage)
	 * @return byte array
	 */
	public byte[] toNetworkByteArray() {
		byte[] blastBodyInBytes = new byte[LENGTH];
		// convert fields to byte arrays
		byte[] rowInBytes = Conversions.intToBytes( blastedPos.row );
		byte[] colInBytes = Conversions.intToBytes( blastedPos.col );
		
		// concatenate field byte arrays
		System.arraycopy(rowInBytes, 0, blastBodyInBytes, 0, 2);
		System.arraycopy(colInBytes, 0, blastBodyInBytes, 2, 2);
		
		return blastBodyInBytes;
	}
}
